package com.ysstech.common.util.fileutil;

import java.io.*;

import com.ysstech.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件上传
 */
@Slf4j
public class FileUploadUtil {
    private static final int MAX_POST_IMAGE_SIZE = 10 * 1024 * 1024;

    /**
     * 文件上传相关代码
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file, String oldFileId) throws Exception {
        File filenew = null;
        try {
            if (null == file || file.isEmpty()) {
                throw new BusinessException("文件为空，请稍后重试！");
            }
            long fileSize = file.getSize();
            if (fileSize > MAX_POST_IMAGE_SIZE) {
                throw new BusinessException("文件大小超过10M，请重新选择上传！");
            }
            //上传到服务器
            filenew = FileUtil.MultipartFileToFile(file);
            if (null == filenew) {
                throw new BusinessException("获取文件失败，请稍后重试！");
            }
            String path = FastDFSClient.uploadFile(filenew, oldFileId);
            if (StringUtils.isBlank(path)) {
                throw new BusinessException("上传文件失败，请稍后重试！");
            }
            return path;
        } catch (BusinessException ex) {
            throw new BusinessException(ex.getMessage());
        } finally {
            FileUtil.delteTempFile(filenew);
        }

    }

}